package com.zklh.leetcode.top100;

import java.util.*;

/**
 * 前k个高频元素算法实现
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/11/29
 */
public class Solution347 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> numToTwice = new HashMap<>();
        for (int num : nums) {
            numToTwice.put(num, numToTwice.getOrDefault(num, 0) + 1);
        }
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(Comparator.comparing(numToTwice::get));
        for (Map.Entry<Integer, Integer> integerIntegerEntry : numToTwice.entrySet()) {
            if (minHeap.size() < k) {
                minHeap.add(integerIntegerEntry.getKey());
            } else {
                if (numToTwice.get(minHeap.peek()) < numToTwice.get(integerIntegerEntry.getKey())) {
                    minHeap.poll();
                    minHeap.add(integerIntegerEntry.getKey());
                }
            }
        }
        return minHeap.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {
        Solution347 solution347 = new Solution347();
        int[] nums = new int[]{4,1,-1,2,-1,2,3};
        int k = 2;
        System.out.println(Arrays.toString(solution347.topKFrequent(nums, 2)));
    }

}